<template>
  <div class="form-content">
    <!-- 表格查询 -->
    <div class="table-search">
      <el-form :inline="true" :model="serachItem" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="serachItem.cardNum" placeholder="请输入卡号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="serachCsInfo">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" @click="addCsInfo">新增</el-button>
        </el-form-item>
        <!-- 导入--导出按钮 -->
        <input type="file" @change="importFile(this)" id="imFile" style="display: none"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
        <el-form-item>
          <el-button type="warning" icon="el-icon-upload2" @click="uploadFile()">导入</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-download" type="success" @click="downloadFile(tableData)">导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 导入预览 -->
      <!--以下a标签不需要内容-->
      <a href="" download="卡号信息表.xlsx" id="hf"></a>
      <!--错误信息提示-->
      <el-dialog title="提示" v-model="errorDialog">
      <span>{{errorMsg}}</span>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="errorDialog=false">确认</el-button>
        </span>
      </el-dialog>
      <!--预览展示导入信息-->
      <el-dialog
        :visible.sync="Import_modal"
        :close-on-click-modal="false"
        center
        :before-close="import_cancel">
        <div class="modal_title">
          <span>卡号信息列表预览</span>
          </div>
        <el-table :data="excelData" tooltip-effect="dark" border style="width: 100%; max-height:450px; overflow-y: auto;">
          <el-table-column label="cardNum" prop="cardNum"></el-table-column>
          <el-table-column label="startTime" prop="startTime" width="180"></el-table-column>
          <el-table-column label="endTime" prop="endTime" width="180"></el-table-column>
          <el-table-column label="status" prop="status"></el-table-column>
          <el-table-column label="imei" prop="imei" show-overflow-tooltip></el-table-column>
          <el-table-column label="remark" prop="remark" show-overflow-tooltip></el-table-column>
        </el-table>
        <!-- 保存--取消按钮 -->
        <el-row :gutter="24" type="flex" justify="end">
          <el-col :span="3">
              <el-button type="primary" @click="importLines_save()">提 交</el-button>
          </el-col>
          <el-col :span="3">
            <el-button @click="import_cancel()">取 消</el-button>
          </el-col>
        </el-row>
      </el-dialog>

    <div class="form-main">
      <!-- 表头标题 -->
      <div class="tb_title">卡号信息</div>
      <!-- 表格 -->
      <div class="listfile">
        <el-table
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          :height="tableHeight"
          :data="tableData">
          <el-table-column prop="cardNum" label="卡号" width="160" show-overflow-tooltip></el-table-column>
          <el-table-column prop="startTime" label="卡号开启时间" width="140"></el-table-column>
          <el-table-column prop="endTime" label="到期时间" width="140"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="140"></el-table-column>
          <el-table-column prop="statusInfo" label="卡号状态" width="90"></el-table-column>
          <el-table-column prop="imei" label="IMEI" width="140"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column label="操作" width="160">
            <template slot-scope="scope">
              <el-button
                size="mini" type="primary" icon="el-icon-edit"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="table_page">
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        ></el-pagination>
      </div>

    </div>

    <!-- 子组件 -->
    <cardModal ref="cardModal1" @submit="submitAddChange" :title='title_name' :historyData='addEdit_data'></cardModal>
  </div>
</template>

<script>
import cardModal from "./cardModal"
import { cardInfoUpload, searchCardPageSize, searchCardInfo } from '@/api/cardApi'
import { nowTime, startRecTime1 } from '@/utils/times'
import XLSX from 'xlsx'
  export default {
    components: {cardModal},
    data() {
      return {
        // 导入导出----start
        new_lineInfos: '',
        Import_modal: false,
        // fullscreenLoading: false, // 加载中
        imFile: '', // 导入文件el
        errorDialog: false, // 错误信息弹窗
        errorMsg: '', // 错误信息内容
        excelData: [ // 测试数据
          {
            cardNum: '', startTime: '', endTime: '', status: '', imei: '', remark: ''
          }
        ],
        // 导入导出----end
        tableHeight: 'calc(100vh - 296px)',
        totalCount: 0, //总条数，总共有多少条数据
        currentPage: 1, // 当前页
        pageSize: 10, // 每页显示多少条
        addEdit_data: {},
        loading: true,
        title_name: '',
        tableData: [],
        serachItem: {
          cardNum: '',
          status: 1,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
      }
    },
    methods: {
      // 导入---导出---start----
      // 保存--导入卡号信息
      importLines_save() {
        let importData = {
          data: this.new_lineInfos
        };
        //回调---卡号信息---导入提交接口
        cardInfoUpload(importData).then((res) => {
          if (res.statusCode == '200') {
            this.loadTableData();
            this.Import_modal = false;
            this.$message({message: '导入成功！！！', type: 'success'});
          } else {
            this.$message.error('导入失败！！！');
          }
        })
      },
      // 导入取消
      import_cancel () {
        this.new_lineInfos = [];
        this.Import_modal = false; // 关闭modal
      },
      // 按钮导入
      uploadFile: function () {
        this.imFile.click();
      },
      // 导入excel
      importFile: function () {
        let obj = this.imFile;
        if (!obj.files) {
          this.fullscreenLoading = false;
          return;
        }
        this.fullscreenLoading = true;
        var f = obj.files[0];
        var reader = new FileReader();
        let $t = this;
        reader.onload = function (e) {
          var data = e.target.result;
          if ($t.rABS) {
            $t.wb = XLSX.read(btoa(this.fixdata(data)), { // 手动转化
              type: 'base64'
            })
          } else {
            $t.wb = XLSX.read(data, {
              type: 'binary'
            })
          }
          let json = XLSX.utils.sheet_to_json($t.wb.Sheets[$t.wb.SheetNames[0]]);
          console.log('1', typeof json);
          $t.dealFile($t.analyzeData(json)); // analyzeData: 解析导入数据
        }
        if (this.rABS) {
          reader.readAsArrayBuffer(f);
        } else {
          reader.readAsBinaryString(f);
        }
      },
      // 此处可以解析导入数据
      analyzeData: function (data) {
        return data;
      },
      // 处理导入的数据
      dealFile: function (data) {
        console.log('处理导入的数据:', data);
        data.map(v=>{
          if ( v.startTime === null || v.endTime === null ){
            v.startTime = nowTime( v.startTime);
            v.endTime = nowTime(v.endTime)
          } else {
            v.startTime = startRecTime1(v.startTime)
            v.endTime = startRecTime1(v.endTime)
          }
        })
        console.log('处理导入的数据++++:', data);
        this.new_lineInfos = data;
        this.imFile.value = '';
        this.fullscreenLoading = false;
        if (data.length <= 0) {
          this.errorDialog = true;
          this.errorMsg = '请导入正确信息';
        } else {
          this.excelData = data;
          this.Import_modal = true; // 打开预览列表
        }
      },
      // 字符串转字符流
      s2ab: function (s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF;
        }
        return buf;
      },
      // 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
      getCharCol: function (n) {
        let s = '';
        let m = 0;
        while (n > 0) {
          m = n % 26 + 1;
          s = String.fromCharCode(m + 64) + s;
          n = (n - m) / 26;
        }
        return s;
      },
      // 文件流转BinaryString
      fixdata: function (data) {
        var o = '';
        var l = 0;
        var w = 10240;
        for (; l < data.byteLength / w; ++l) {
          o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
        }
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
        return o;
      },
      // 按钮导出
      downloadFile: function (exportAllData, type) {
        var exportData1 = [...exportAllData];
        // console.log("hahhahah", exportAllData, exportData1)
        var tmpdata = exportData1[0];
        exportData1.unshift({})
        var keyMap = []; // 获取keys
        for (var k in tmpdata) {
          keyMap.push(k);
          exportData1[0][k] = k;
        }
        var tmpdata = []; // 用来保存转换好的historyData
        exportData1.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
          v: v[k],
          position: (j > 25 ? getCharCol(j) : String.fromCharCode(65 + j)) + ( i + 1)
        }))).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = {
          v: v.v
        })
        var outputPos = Object.keys(tmpdata); // 设置区域,比如表格从A1到D10
        var tmpWB = {
          SheetNames: ['mySheet'], // 保存的表标题
          Sheets: {
            'mySheet': Object.assign({},
              tmpdata, // 内容
              {
                '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
              })
          }
        }
        let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
          {bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'}// 这里的数据是用来定义导出的格式类型
        ))], {
          type: ''
        }) // 创建二进制对象写入转换好的字节流
        var href = URL.createObjectURL(tmpDown); // 创建对象超链接
        document.getElementById('hf').href = href; // 绑定a标签
        document.getElementById('hf').click(); // 模拟点击实现下载
        setTimeout(function () { // 延时释放
          URL.revokeObjectURL(tmpDown); // 用URL.revokeObjectURL()来释放这个object URL
        }, 100)
      },
      // 导入---导出---end------

      // 新增--保存后，子传给父组件
      submitAddChange () {
        this.allFindCsInfo(); // 条件查询
      },
      //添加
      addCsInfo(){
        this.$refs.cardModal1.modal1 = true;
        this.title_name = '新增卡号';
        // this.$refs.cardModal1.addEdmitFun(); // 父调子组件的方法
      },
      //卡号查询(条件查询接口)
      serachCsInfo() {
        //回调接口
        searchCardInfo(this.serachItem).then((res)=>{
          if (res.statusCode == "200"){
            this.tableData = [];
            console.log("搜索：", res.data)
            this.tableData = res.data.content;
            this.tableData.map(v=>{
              if (v.status == 1){
                v.statusInfo = '正常'
              }
            })
            this.totalCount = res.data.total;
          }
        })
      },
      // 卡号分页查询 (查询所有)
      allFindCsInfo(){
        let _data = {
          status: 1,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        };
        //回调接口
        searchCardPageSize(_data).then((res)=>{
          console.log("查询所有:", res.data);
          if (res.statusCode == "200"){
            this.loading = false;
            this.tableData = res.data.content;
            this.tableData.map(v=>{
              if (v.status == 1){
                  v.statusInfo = '正常'
              }
            })
            this.totalCount = res.data.total;
          }
        })
      },
      //编辑
      handleEdit(index, row) {
        this.addEdit_data = JSON.parse(JSON.stringify(row));
        // console.log("编辑:", index, row, this.addEdit_data);
        this.$refs.cardModal1.modal1 = true;
        this.title_name = '编辑卡号';
        //  this.$refs.cardModal1.addEdmitFun(); // 父调子组件的方法
      },
      // 分页
      handleCurrentChange(newPage) {
        this.currentPage = newPage
        this.loadTableData()
      },
      //每页
      handleSizeChange(val) {
        this.pageSize = val
        this.loadTableData()
      },

      //封装分页接口
      loadTableData(){
        if (this.serachItem.cardNum) {
          //调条件查询接口
          this.serachCsInfo();
        } else {
          //调查询所有的接口
          this.allFindCsInfo();
        }

      }
    },
    created(){},
    mounted(){
      this.loadTableData();
      // 导入---
      this.imFile = document.getElementById('imFile');
    },
    destroyed() {
      this.$destroy();
      this.tableData = [];
      this.page_Data = [];
    }
  }
</script>
